#include "deviceinfowindow.h"
#include "ui_deviceinfowindow.h"
#include <QMessageBox>
#include <QJsonDocument>
#include <QJsonValue>
#include <QDebug>

DeviceInfoWindow::DeviceInfoWindow(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::DeviceInfoWindow)
    , m_baifaClient(nullptr)
    , m_refreshTimer(nullptr)
{
    ui->setupUi(this);
    setupUI();
    setupConnections();
    
    // 初始化巴法云客户端
    m_baifaClient = new BaifaCloudClient(this);
    
    // 连接巴法云客户端信号
    connect(m_baifaClient, &BaifaCloudClient::deviceListReceived,
            this, &DeviceInfoWindow::onDeviceListReceived);
    connect(m_baifaClient, &BaifaCloudClient::deviceDataReceived,
            this, &DeviceInfoWindow::onDeviceDataReceived);
    connect(m_baifaClient, &BaifaCloudClient::errorOccurred,
            this, &DeviceInfoWindow::onErrorOccurred);
    
    // 初始化定时器
    m_refreshTimer = new QTimer(this);
    m_refreshTimer->setInterval(5000); // 5秒刷新一次
    connect(m_refreshTimer, &QTimer::timeout, this, &DeviceInfoWindow::onRefreshTimer);
    
    // 自动获取设备列表
    onRefreshClicked();
}

DeviceInfoWindow::~DeviceInfoWindow()
{
    if (m_refreshTimer && m_refreshTimer->isActive()) {
        m_refreshTimer->stop();
    }
    delete ui;
}

void DeviceInfoWindow::setupUI()
{
    // 设置窗口属性
    setWindowFlags(Qt::Window | Qt::WindowCloseButtonHint | 
                   Qt::WindowMinimizeButtonHint | Qt::WindowMaximizeButtonHint);
    setAttribute(Qt::WA_DeleteOnClose);
    
    // 初始状态
    updateConnectionStatus(false);
}

void DeviceInfoWindow::setupConnections()
{
    connect(ui->refreshButton, &QPushButton::clicked, this, &DeviceInfoWindow::onRefreshClicked);
    connect(ui->closeButton, &QPushButton::clicked, this, &DeviceInfoWindow::onCloseClicked);
    connect(ui->deviceListWidget, &QListWidget::itemSelectionChanged,
            this, &DeviceInfoWindow::onDeviceSelectionChanged);
}

void DeviceInfoWindow::onRefreshClicked()
{
    ui->statusLabel->setText("连接状态: 正在连接...");
    ui->statusLabel->setStyleSheet("font-size: 14px; color: #f39c12; font-weight: bold;");
    
    if (m_baifaClient) {
        m_baifaClient->getDeviceList();
    }
}

void DeviceInfoWindow::onCloseClicked()
{
    if (m_refreshTimer && m_refreshTimer->isActive()) {
        m_refreshTimer->stop();
    }
    close();
}

void DeviceInfoWindow::onDeviceSelectionChanged()
{
    // 先停止定时器，避免数据冲突
    if (m_refreshTimer->isActive()) {
        m_refreshTimer->stop();
    }
    
    QListWidgetItem *currentItem = ui->deviceListWidget->currentItem();
    if (currentItem) {
        QString topic = currentItem->data(Qt::UserRole).toString();
        if (!topic.isEmpty() && topic != m_currentTopic) {
            m_currentTopic = topic;
            // 立即获取设备数据（updateDeviceData会负责清空UI）
            if (m_baifaClient) {
                m_baifaClient->getDeviceData(topic);
            }
            // 启动定时刷新
            m_refreshTimer->start();
        }
    } else {
        m_currentTopic.clear();
        clearDeviceData();
    }
}

void DeviceInfoWindow::onDeviceListReceived(const QJsonArray &devices)
{
    updateConnectionStatus(true);
    updateDeviceList(devices);
}

void DeviceInfoWindow::onDeviceDataReceived(const QString &topic, const QJsonObject &data)
{
    if (topic == m_currentTopic) {
        updateDeviceData(data);
    }
}

void DeviceInfoWindow::onErrorOccurred(const QString &errorMsg)
{
    updateConnectionStatus(false);
    QMessageBox::warning(this, "连接错误", "巴法云连接失败:\n" + errorMsg);
    qDebug() << "BaifaCloud Error:" << errorMsg;
}

void DeviceInfoWindow::onRefreshTimer()
{
    if (!m_currentTopic.isEmpty() && m_baifaClient) {
        m_baifaClient->getDeviceData(m_currentTopic);
    }
}

void DeviceInfoWindow::updateDeviceList(const QJsonArray &devices)
{
    ui->deviceListWidget->clear();
    
    for (const QJsonValue &deviceValue : devices) {
        QJsonObject device = deviceValue.toObject();
        QString name = device["name"].toString();
        QString topic = device["topic"].toString();
        QString status = device["status"].toString();
        
        if (!name.isEmpty() && !topic.isEmpty()) {
            QListWidgetItem *item = new QListWidgetItem();
            item->setText(QString("%1\n主题: %2\n状态: %3")
                         .arg(name)
                         .arg(topic)
                         .arg(status.isEmpty() ? "未知" : status));
            item->setData(Qt::UserRole, topic);
            ui->deviceListWidget->addItem(item);
        }
    }
    
    if (ui->deviceListWidget->count() == 0) {
        QListWidgetItem *item = new QListWidgetItem("暂无设备");
        item->setFlags(item->flags() & ~Qt::ItemIsSelectable);
        ui->deviceListWidget->addItem(item);
    }
}

void DeviceInfoWindow::updateDeviceData(const QJsonObject &data)
{
    // 构建HTML格式的设备数据显示
    QString htmlContent = "<html><head><style>";
    htmlContent += "body { font-family: 'Microsoft YaHei', Arial, sans-serif; margin: 10px; }";
    htmlContent += "h2 { color: #2c3e50; text-align: center; margin-bottom: 5px; }";
    htmlContent += "h3 { color: #34495e; margin-top: 15px; margin-bottom: 8px; }";
    htmlContent += "p { margin: 5px 0; line-height: 1.4; }";
    htmlContent += ".time { color: #7f8c8d; font-size: 12px; text-align: center; margin-bottom: 15px; }";
    htmlContent += ".data-item { background-color: #f8f9fa; padding: 8px; margin: 3px 0; border-radius: 4px; }";
    htmlContent += ".key { font-weight: bold; color: #2c3e50; }";
    htmlContent += ".value { color: #34495e; margin-left: 10px; }";
    htmlContent += "</style></head><body>";
    
    // 添加设备名称标题
    QListWidgetItem *currentItem = ui->deviceListWidget->currentItem();
    if (currentItem) {
        QString deviceName = currentItem->text().split("\n")[0];
        htmlContent += "<h2>" + deviceName + " - 实时数据</h2>";
    }
    
    // 添加数据更新时间
    htmlContent += "<p class='time'>更新时间: " + QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss") + "</p>";
    htmlContent += "<hr>";
    
    // 显示设备数据
    if (data.isEmpty()) {
        htmlContent += "<p style='text-align: center; color: #95a5a6; font-size: 16px; margin-top: 50px;'>暂无数据</p>";
    } else {
        // 遍历数据对象的所有键值对
        for (auto it = data.begin(); it != data.end(); ++it) {
            QString key = it.key();
            QJsonValue value = it.value();
            
            htmlContent += "<div class='data-item'>";
            htmlContent += "<span class='key'>" + key + ":</span>";
            
            if (value.isString()) {
                htmlContent += "<span class='value'>" + value.toString() + "</span>";
            } else if (value.isDouble()) {
                htmlContent += "<span class='value'>" + QString::number(value.toDouble()) + "</span>";
            } else if (value.isBool()) {
                QString boolText = value.toBool() ? QString::fromUtf8("是") : QString::fromUtf8("否");
                htmlContent += "<span class='value'>" + boolText + "</span>";
            } else {
                htmlContent += "<span class='value'>" + QJsonDocument(QJsonObject{{key, value}}).toJson(QJsonDocument::Compact) + "</span>";
            }
            
            htmlContent += "</div>";
        }
    }
    
    htmlContent += "</body></html>";
    
    // 设置HTML内容到TextBrowser
    ui->deviceDataTextBrowser->setHtml(htmlContent);
}

void DeviceInfoWindow::clearDeviceData()
{
    // 设置默认HTML内容
    QString defaultHtml = "<html><head><style>";
    defaultHtml += "body { font-family: 'Microsoft YaHei', Arial, sans-serif; margin: 10px; }";
    defaultHtml += "</style></head><body>";
    defaultHtml += "<p style='text-align: center; font-size: 18px; font-weight: bold; color: #2c3e50; margin-top: 100px;'>请选择设备查看数据</p>";
    defaultHtml += "</body></html>";
    
    ui->deviceDataTextBrowser->setHtml(defaultHtml);
}

void DeviceInfoWindow::updateConnectionStatus(bool connected)
{
    if (connected) {
        ui->statusLabel->setText("连接状态: 已连接");
        ui->statusLabel->setStyleSheet("font-size: 14px; color: #27ae60; font-weight: bold;");
    } else {
        ui->statusLabel->setText("连接状态: 未连接");
        ui->statusLabel->setStyleSheet("font-size: 14px; color: #e74c3c; font-weight: bold;");
    }
}